<template>
    <el-row class="contain-box">
        <site-nav/>
        <div class="view-body">
            <el-row>
                <el-form class="inline-form" inline>
                    <el-form-item>
                        <el-button @click="addEntity" type="primary"><i class="el-icon-plus el-icon--left"/>添加应用
                        </el-button>
                    </el-form-item>
                    <el-form-item label="appId">
                        <el-input @clear="search" clearable placeholder="请输入appId" v-model="params.appId"/>
                    </el-form-item>
                    <el-form-item label="应用名称">
                        <el-input @clear="search" clearable placeholder="请输入应用名称" v-model="params.appNameLike"/>
                    </el-form-item>
                    <el-form-item label="类型">
                        <el-select clearable filterable placeholder="请选择" v-model="params.wxAppType">
                            <el-option value="" label="不限"/>
                            <el-option v-for="(label, key) in wxAppTypeMap" :key="key" :value="key" :label="label"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="启用">
                        <el-select clearable filterable placeholder="请选择" v-model="params.enable">
                            <el-option value="" label="不限"/>
                            <el-option :value="true" label="是"/>
                            <el-option :value="false" label="否"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="search" icon="el-icon-search" type="primary">搜索</el-button>
                    </el-form-item>
                </el-form>
            </el-row>
            <el-row>
                <el-col>
                    <el-table :data="list" size="small" border>
                        <el-table-column label="appId/企业应用ID" align="center" width="200">
                            <template slot-scope="scope">
                                <template v-if="scope.row.wxAppType === 'CP'">{{scope.row.corpId}}:{{scope.row.agentId}}</template>
                                <template v-else>{{scope.row.appId}}</template>
                            </template>
                        </el-table-column>
                        <el-table-column prop="appName" label="应用名称" align="center"/>
                        <el-table-column label="应用类型" align="center" width="100">
                            <template slot-scope="scope">{{wxAppTypeMap[scope.row.wxAppType]}}</template>
                        </el-table-column>
                        <el-table-column label="启用" align="center" width="60">
                            <template slot-scope="scope">
                                <commons-enable :value="scope.row.enable"/>
                            </template>
                        </el-table-column>
                        <el-table-column prop="remark" label="备注" align="center"/>
                        <el-table-column label="操作" align="left" header-align="center" width="450">
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" @click="updateEntity(scope.row)">修改</el-button>
                                <el-button size="mini" type="danger" @click="deleteEntity(scope.row)">删除</el-button>
                                <el-button size="mini" @click="viewUsers(scope.row)">用户列表</el-button>
                                <template v-if="scope.row.wxAppType === 'MP'">
                                    <el-button size="mini" @click="sendTemplateMsg(scope.row)">发送模板消息</el-button>
                                    <template v-if="scope.row.userSyncProgressing">
                                        <el-popover
                                                class="progress"
                                                placement="bottom"
                                                title="同步进度"
                                                width="200"
                                                trigger="click"
                                                :content="scope.row.userSyncProgressMsg">
                                            <el-button size="mini" slot="reference">同步用户中</el-button>
                                        </el-popover>
                                    </template>
                                    <template v-else>
                                        <el-button size="mini" @click="syncUsers(scope.row)">同步用户</el-button>
                                    </template>
                                </template>
                                <template v-if="scope.row.wxAppType === 'MINI_APP'">
                                    <el-button size="mini" @click="sendSubscribeMsg(scope.row)">发送订阅消息</el-button>
                                </template>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
            <el-row>
                <el-col class="pagination">
                    <el-pagination :current-page="params.pageId" :page-size="params.pageSize" :total="count"
                                   @current-change="currentChange" background layout="total, prev, pager, next"/>
                </el-col>
            </el-row>
        </div>
        <el-dialog :before-close="dialogClose" :title="dialog.isAdd ? '新增应用' : '修改应用'" :visible.sync="dialog.show"
                   class="dialog">
            <el-form :model="info" :rules="rules" label-width="120px" ref="form" size="small">
                <template v-if="info.wxAppType === 'CP'">
                    <el-form-item :required="true" label="企业ID" prop="corpId">
                        <el-input v-if="dialog.isAdd" type="text" v-model="info.corpId"/>
                        <template v-else>{{info.corpId}}</template>
                    </el-form-item>
                    <el-form-item :required="true" label="应用ID" prop="agentId">
                        <el-input v-if="dialog.isAdd" type="number" v-model="info.agentId"/>
                        <template v-else>{{info.agentId}}</template>
                    </el-form-item>
                </template>
                <template v-else>
                    <el-form-item :required="true" label="AppId" prop="appId">
                        <el-input v-if="dialog.isAdd" type="text" v-model="info.appId"/>
                        <template v-else>{{info.appId}}</template>
                    </el-form-item>
                </template>
                <el-form-item :required="true" label="应用名称" prop="appName">
                    <el-input type="text" v-model="info.appName"/>
                </el-form-item>
                <el-form-item label="应用类型">
                    <el-radio-group v-if="dialog.isAdd" v-model="info.wxAppType" @change="changeType">
                        <el-radio v-for="(label, key) in wxAppTypeMap" :key="key" :label="key">{{label}}</el-radio>
                    </el-radio-group>
                    <template v-else>{{wxAppTypeMap[info.wxAppType]}}</template>
                </el-form-item>
                <el-form-item :required="true" label="secret" prop="secret">
                    <el-input type="text" v-model="info.secret"/>
                </el-form-item>
                <el-form-item label="token" prop="token">
                    <el-input type="text" v-model="info.token"/>
                </el-form-item>
                <el-form-item label="aesKey" prop="aesKey">
                    <el-input type="text" v-model="info.aesKey"/>
                </el-form-item>
                <el-form-item label="消息数据格式" v-if="info.wxAppType === 'MINI_APP'">
                    <el-radio-group v-model="info.msgDataFormat">
                        <el-radio v-for="(label, key) in wxMsgDataFormatMap" :key="key" :label="key">{{label}}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="启用">
                    <el-radio-group v-model="info.enable">
                        <el-radio :label="false">否</el-radio>
                        <el-radio :label="true">是</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input type="text" v-model="info.remark"/>
                </el-form-item>
            </el-form>
            <div class="dialog-footer" slot="footer">
                <el-button @click="dialogClose" size="mini">取 消</el-button>
                <el-button :loading="dialog.submitting" @click="dialogSubmit" size="mini" type="primary">确 定</el-button>
            </div>
        </el-dialog>
    </el-row>
</template>
<script lang="ts">
  import {PARAMS} from '@/api/http';
  import DialogInfo from '@/structure/dialogInfo';
  import FormRules from '@/structure/formRules';
  import {ElForm} from 'element-ui/types/form';
  import {Component, Vue} from 'vue-property-decorator';
  import Api from '../../api/wxAppApi';
  import WxMpUserApi from '../../api/wxMpUserApi';
  import {UserSyncProcessMap} from '../../structure/userSyncProcess';
  import Entity from '../../structure/wxApp';
  import WxAppType, {WxAppTypeMap} from '../../structure/wxAppType';
  import {WxMsgDataFormatMap} from '../../structure/wxMsgDataFormat';

  @Component
  export default class Page extends Vue {
    public wxAppTypeMap = WxAppTypeMap;
    public wxMsgDataFormatMap = WxMsgDataFormatMap;
    public list: Entity[] = [];
    public count: number | null = null;
    public params: PARAMS = {
      pageId: 1,
      appId: '',
      appNameLike: '',
      wxAppType: '',
      enable: ''
    };
    public dialog: DialogInfo = new DialogInfo();
    public info: Entity = new Entity();
    public rules: FormRules = {
      appId: [
        {
          required: true,
          message: '请输入appId'
        }
      ],
      corpId: [
        {
          required: true,
          message: '请输入企业ID'
        }
      ],
      agentId: [
        {
          required: true,
          message: '请输入应用ID'
        }
      ],
      secret: [
        {
          required: true,
          message: '请输入secret'
        }
      ],
      wxAppType: [
        {
          required: true,
          message: '请选择微信应用类型'
        }
      ],
      appName: [
        {
          required: true,
          message: '请选择微信应用名称'
        }
      ]
    };

    public get form(): ElForm {
      return this.$refs.form as ElForm;
    }

    public changeType(wxAppType: WxAppType): void {
      if (wxAppType === 'CP') {
        this.rules.appId[0].required = false;
        this.rules.corpId[0].required = true;
        this.rules.agentId[0].required = true;
      } else {
        this.rules.appId[0].required = true;
        this.rules.corpId[0].required = false;
        this.rules.agentId[0].required = false;
      }
    }

    public created(): void {
      this.getDataList();
    }

    public search(): void {
      this.currentChange(1);
    }

    public getDataList(): void {
      Api.findList(this.params).then((res) => {
        res.list.forEach((item) => {
          item.userSyncProgressing = false;
          item.userSyncProgressMsg = '';
        });
        this.list = res.list;
        this.count = res.count;
      });
    }

    public currentChange(val: number): void {
      this.params.pageId = val;
      this.getDataList();
    }

    public addEntity(): void {
      this.dialog.isAdd = true;
      this.dialog.show = true;
      this.info = new Entity();
    }

    public updateEntity(info: Entity): void {
      this.info = {...info};
      this.dialog.isAdd = false;
      this.dialog.show = true;
    }

    public deleteEntity(info: Entity): void {
      this.$confirm('是否删除该应用?', '删除应用', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Api.delete(info.appId).then(() => {
          this.getDataList();
          this.$message.success('删除成功!');
        });
      });
    }

    public dialogClose(): void {
      this.dialog.show = false;
      this.info = new Entity();
      this.form.resetFields();
    }

    public dialogSubmit(): void {
      this.form.validate((valid) => {
        if (!valid) {
          return false;
        }

        this.dialog.submitting = true;

        const func = this.dialog.isAdd ? Api.save : Api.update;
        const msg = this.dialog.isAdd ? '添加应用成功' : '编辑应用成功';

        func.call(Api, this.info).then(() => {
          this.getDataList();
          this.dialogClose();
          this.dialog.submitting = false;
          this.$message.success(msg);
        }).catch(() => {
          this.dialog.submitting = false;
        });
      });
    }

    public viewUsers(info: Entity): void {
      this.$router.push({
        name: 'WeChat_User',
        query: {
          appId: info.appId,
          showBackButton: 'true',
          hiddenAppSelect: 'true'
        }
      });
    }

    public getUserSyncStatus(info: Entity): void {
      const appId = info.appId;
      WxMpUserApi.getUserSyncStatus(appId).then((res) => {
        const progressing = res.process !== 'FREE';
        info.userSyncProgressing = progressing;
        if (res.process === 'GETTING_USER_DETAIL') {
          info.userSyncProgressMsg = `${res.complete}/${res.count}已完成`;
        } else if (res.process === 'EXCEPTION') {
          info.userSyncProgressMsg = UserSyncProcessMap[res.process] + ':' + res.errorMessage;
        } else {
          info.userSyncProgressMsg = UserSyncProcessMap[res.process];
        }

        if (progressing) {
          setTimeout(() => {
            this.getUserSyncStatus(info);
          }, 1000);
        }
      });
    }

    public syncUsers(info: Entity): void {
      WxMpUserApi.userSync(info.appId).then(() => {
        this.$message.success('同步任务提交成功');
        this.getUserSyncStatus(info);
      }).catch(() => {
        this.getUserSyncStatus(info);
      });
    }

    public sendSubscribeMsg(info: Entity): void {
      this.$router.push({
        name: 'WeChat_SendSubscribeMsg',
        params: {
          appId: info.appId
      }
    });
  }

  public sendTemplateMsg(info: Entity): void {
    this.$router.push({
      name: 'WeChat_SendTemplateMsg',
      params: {
        appId: info.appId
      }
    });
  }
}
</script>
<style lang="scss" scoped>
    .progress {
        margin-left: 10px;
    }
</style>
